import base64
import json
import uuid

from util.kafka_producer_connect import KafkaProducerConnect
from util.redis_connect import RedisPoolConnect
from util.response_format import ResponseFormat
# 连接对象放在函数外部，定义为全局变量，可以减少连接实例的创建销毁带来的性能浪费
# 消息队列生产者
PRODUCER = KafkaProducerConnect()
# 红包剩余金额剩余个数缓存统计
REDIS_POOL_INFO = RedisPoolConnect(0)


def handler(event, context):
    """
    发红包Api
    post请求参数
    totalAmount 红包总额
    totalCount 红包个数
    topicId 消息队列标题名，因influxdb的原因，topic_id不能带有“-”号
    userName 用户名
    message 消息内容
    """
    logger = context.getLogger()
    params = json.loads(base64.b64decode(event["body"]).decode().replace("'", '"'))
    logger.info(params)
    total_amount = float(params.get("totalAmount"))
    total_count = int(params.get("totalCount"))
    topic_id = params.get("topicId")
    user_name = params.get("userName")
    message = params.get("message")
    red_envelope_id = str(uuid.uuid4())
    logger.info(red_envelope_id)
    try:
        # 记录红包剩余信息
        REDIS_POOL_INFO.set_key_value(
            red_envelope_id, json.dumps({"totalAmount": total_amount, "totalCount": total_count}))
    except ConnectionError:
        logger.error("redis连接错误，请检查redis配置信息")
        return ResponseFormat({"code": 500, "msg": "服务器错误"}, 500).to_json()
    # 消息发送
    msg = {"redEnvelopeId": red_envelope_id, "message": message, "messageType": 2, "userName": user_name}
    try:
        PRODUCER.send_msg(topic_id, msg)
    except ConnectionError:
        logger.error("kafka连接错误，请检查kafka配置信息")
        return ResponseFormat({"code": 500, "msg": "服务器错误"}, 500).to_json()
    return ResponseFormat({"code": 200, "msg": "红包发送成功"}, 200).to_json()
